import xml.etree.ElementTree as ET
from os import getcwd

# sets = [('2007', 'train'), ('2007', 'val'), ('2007', 'test')]
sets = ['train', 'test']
# classes = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
classes = ["seeding"]
datasetspath = 'ImageSets/seeding2nd'
xmlfilepath = datasetspath + '/VOCAnnotations'
txtsavepath = datasetspath + '/COCOTxt'


def convert_loc(size, box):
    dw = 1. / size[0]
    dh = 1. / size[1]
    x = (box[0] + box[1]) / 2.0
    y = (box[2] + box[3]) / 2.0
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh
    return (x, y, w, h)


def convert_annotation(image_id, list_file):
    # in_file = open('VOCdevkit/VOC%s/Annotations/%s.xml'%(year, image_id))
    w = 0
    h = 0
    in_file = open(xmlfilepath + '/%s.xml' % image_id, encoding='utf-8')
    tree = ET.parse(in_file)
    root = tree.getroot()
    for obj in root.iter('size'):
        w = int(obj.find('width').text)
        h = int(obj.find('height').text)

    for obj in root.iter('object'):
        difficult = obj.find('difficult').text
        cls = obj.find('name').text
        if cls not in classes or int(difficult) == 1:
            continue
        cls_id = classes.index(cls)
        xmlbox = obj.find('bndbox')
        b = (int(xmlbox.find('xmin').text), int(xmlbox.find('xmax').text), int(xmlbox.find('ymin').text),
             int(xmlbox.find('ymax').text))
        b = convert_loc((w, h), b)
        list_file.write(str(cls_id) + " " + " ".join([str(a) for a in b]) + ' ' + '\n')


# wd = getcwd()

# for year, image_set in sets:
#     image_ids = open('VOCdevkit/VOC%s/ImageSets/Main/%s.txt' % (year, image_set)).read().strip().split()
#     list_file = open('%s_%s.txt' % (year, image_set), 'w')
#     for image_id in image_ids:
#         list_file.write('%s/VOCdevkit/VOC%s/JPEGImages/%s.jpg' % (wd, year, image_id))
#         convert_annotation(year, image_id, list_file)
#         list_file.write('\n')
#     list_file.close()
for image_set in sets:
    image_ids = open(datasetspath + '/%s.txt' % image_set).read().strip().split()

    for image_id in image_ids:
        list_file = open(txtsavepath + '/%s.txt' % image_id, 'w')
        # list_file.write('%s/VOCdevkit/VOC%s/JPEGImages/%s.jpg' % (wd, year, image_id))
        convert_annotation(image_id, list_file)
        # list_file.write('\n')
        list_file.close()
